<!-- eslint-disable vue/v-on-event-hyphenation -->
<template>
  <a-modal
    v-model:visible="visible"
    draggable
    width="500px"
    @before-ok="handleBeforeOk"
    @cancel="handleChangeVisible"
    @close="close"
  >
    <template #title> {{ title }}</template>
    <a-form
      ref="formRef"
      :model="formData"
      class="form"
      :label-col-props="{ span: 4 }"
      :wrapper-col-props="{ span: 16 }"
    >
      <a-form-item field="id" label="用户">
        <Icon-Select-More-Option
          v-model:list="roleDetailData.users"
          :scroll-opt="{
            open: true,
            maxHeight: 300,
          }"
          :styles="{ minHeight: '150px', minWidth: '100%' }"
          :is-disable="isEdit"
          @handle-chang-list="handleClickToClose($event)"
          @handle-icon-click="handleIconClick()"
        ></Icon-Select-More-Option>
      </a-form-item>
    </a-form>
    <SelectUsersBook
      ref="selectUsersBookRef"
      @change="userSelection"
    ></SelectUsersBook>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, defineProps } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { userVo } from '@/api/role';
  import { Menu } from '@/api/menu';
  import {
    selectOtherUserByBindUser,
    bindUserAndOtherUser,
    UserPageQueryVO,
  } from '@/api/user';
  import IconSelectMoreOption from '@/components/icon-select-more-option/index.vue';

  defineProps({
    title: {
      type: String,
      default: '可用用户授权',
    },
  });

  const isEdit = ref(true);
  const formRef = ref();
  const visible = ref(false);
  const RoleDetailForm = () => {
    return {
      users: [] as Array<userVo>,
      userGroups: [] as Array<userVo>,
    };
  };
  const formData = ref<UserPageQueryVO[]>([]);
  const roleDetailData = ref(RoleDetailForm());
  const selectUsersBookRef = ref();

  // 根据id查询绑定的用户
  const fetchUserData = async (id: string) => {
    const { data } = await selectOtherUserByBindUser(id);
    roleDetailData.value.users = (data || []) as any;
  };
  const menuIdValue = ref();
  function handleChangeVisible(obj: Menu) {
    visible.value = !visible.value;
    if (!visible.value) formData.value = [];
    if (visible.value && obj) {
      fetchUserData(obj.id);
      menuIdValue.value = obj.id;
      formData.value = JSON.parse(JSON.stringify(obj));
    }
  }
  const handleClickToClose = (
    list: { id: string; loginName: string; name: string }[]
  ) => {
    roleDetailData.value.users = list;
  };
  const userSelection = (
    list: { id: string; loginName: string; name: string }[]
  ) => {
    roleDetailData.value.users = [
      ...roleDetailData.value.users,
      ...list,
    ].filter((item, index, self) => {
      return (
        index ===
        self.findIndex(
          (obj) => obj.id === item.id && obj.loginName === item.loginName
        )
      );
    });
  };
  const handleIconClick = () => {
    selectUsersBookRef.value.handleChangeVisible();
  };

  const emit = defineEmits(['refresh']);

  function handleBeforeOk(done: any) {
    formRef.value.validate((valid: any) => {
      if (valid) {
        done(false);
      }
      const param = {
        businessId: menuIdValue.value,
        userIds: roleDetailData.value.users.map((item) => item.id),
      };
      bindUserAndOtherUser(param)
        .then(() => {
          Message.success('操作成功');
          emit('refresh');
          done();
        })
        .catch(() => {
          done(false);
        });
    });
  }
  const close = () => {
    visible.value = false;
    formData.value = [];
    formRef.value.clearValidate();
  };
  defineExpose({ handleChangeVisible });
</script>
